const qs = require('querystring')
const axios = require('axios')
const { session } = require('electron')
const iconv = require('iconv-lite') // 转码
const path = require('path')

function getCookie(url) {
  return new Promise((resolve, reject) => {
    session.defaultSession.cookies.get({url}, (error, cookies) => {
      if (error) return reject(error)
      resolve(cookies)
    })
  })
}

const defaultAxiosConf = {
  timeout: 15000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'Referer': 'http://www.qq.com/',
    'Accept-Language': 'zh-CN,zh;q=0.9'
  },
  baseURL: '/api'
}

let datas = {
  g_tk: '',
  cookies: '',
  cookieMap: {}
}

function request(params = {}, fn) {
  if (typeof fn === 'function') fn(true)
  if (params.data) params.data = qs.stringify(params.data)
  if (!params.method) params.method = 'get'
  if (params.method.toLowerCase() === 'get') params.url += `?${qs.stringify(params.data)}`
  defaultAxiosConf.headers.cookie = datas.cookies
  return axios({...defaultAxiosConf, ...params}).then(res => {
    if (typeof fn === 'function') fn(false)
    return res.data
  }).catch(err => {
    if (typeof fn === 'function') fn(false)
    throw err
  })
}

function requestGBK(params = {}, fn) {
  if (typeof fn === 'function') fn(true)
  if (params.data) params.data = qs.stringify(params.data)
  if (!params.method) params.method = 'get'
  if (params.method.toLowerCase() === 'get') params.url += `?${qs.stringify(params.data)}`
  const extra = {
    responseType: 'stream'
  }
  defaultAxiosConf.headers.cookie = datas.cookies
  return axios({...defaultAxiosConf, ...extra, ...params}).then(res => {
    if (typeof fn === 'function') fn(false)
    let converterStream = iconv.decodeStream('GBK')
    res.data.pipe(converterStream)
    let data = ''
    return new Promise((resolve, reject) => {
      converterStream.on('data', chunk => {
        data += chunk
      })
      converterStream.on('end', () => {
        resolve(data)
      })
    })
  }).catch(err => {
    if (typeof fn === 'function') fn(false)
    throw err
  })
}

module.exports = {
  request,
  getCookie,
  datas,
  requestGBK,
  current_dir: path.resolve(__dirname)
}